import React, {PureComponent} from 'react';
import BaseComponent from '../base/BaseComponent';
import {connect} from 'react-redux';
import {
  StyleSheet,
  ImageBackground,
  Platform,
  Text,
  Button,
  TextInput,
  View,
  FlatList,
  RefreshControl,
  KeyboardAvoidingView,
  TouchableOpacity,
  Image,
  Keyboard,
  TouchableWithoutFeedback,
} from 'react-native';
import {LinearButton, TextButton} from '../../components/Button';
import I18n from 'react-native-i18n';
import {NormalHeader} from '../../components/NavigationHeader';
import {createChannel} from '../../api/channel/index';
import {ScrollView} from 'react-native-gesture-handler';
import * as ImagePicker from 'react-native-image-picker';
import {updateUserInfo, setCurrentRoom, setRoomKey} from '../../redux/action';
import {queryAuctionList} from '../../api/auction';
import {BASE_API} from '../../config';
import moment from 'moment';
import LinearGradient from 'react-native-linear-gradient';
import {showToast} from '../../components/Toast';

class CreateRoomScreen extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      name: '',
      introduction: '',
      password: '',
      showAdvance: false,
      showAuction: false,
      auctions: [],
      notice: '',
      showPassword: false,
      createPaidRoom: 0,
    };
  }

  createRoom = () => {
    Keyboard.dismiss();

    if (this.state.querying) {
      return;
    }

    if (this.state.name.length == 0) {
      showToast('please input correct topic');
      return;
    }

    if (this.state.notice.length == 0) {
      showToast('please input correct notice');
      return;
    }

    this.setState({
      querying: true,
    });
    // this._showLoading('creating...');

    let auctionIds = this.state.auctions
      .filter((item) => item.selected)
      .map((item) => item.auctionId)
      .join(',');

    let params = {
      userToken: this.props.userInfo.token,
      name: this.state.name,
      introduction: this.state.introduction,
      notice: this.state.notice,
      password: this.state.password,
      auctionIds,
      paid: this.state.createPaidRoom ? 1 : 0,
    };

    if (this.state.password.length == 0) {
      delete params.password;
    }

    if (this.state.introduction.length == 0) {
      delete params.introduction;
    }

    createChannel(
      params,
      this.state.topicImage
        ? [
            {
              uri: this.state.topicImage,
              name: 'images',
            },
          ]
        : null,
    )
      .then(async (res) => {
        await this.props.updateUserInfo({
          ...this.props.userInfo,
          isSpeaker: 1,
          isRoomOwner: true,
          micphoneState: true,
        });

        //设置当前频道
        this.props.setCurrentRoom(res.data);

        //回调Home页面加入频道
        await this.props.navigation.state.params.join();

        this.setState({
          querying: false,
        });

        this.props.navigation.navigate('Room', {
          from: 'home',
          channel: res.data,
          backKey: this.props.navigation.state.key,
        });
      })
      .catch((err) => {
        this.setState({
          querying: false,
        });
        showToast(err);
        console.log('创建房间失败' + err);
      });
  };

  componentDidMount() {
    super.componentDidMount();
    this.getSelfAuction();
    this.props.setRoomKey(this.props.navigation.state.key);
  }

  getSelfAuction = () => {
    queryAuctionList({
      userToken: this.props.userInfo.token,
      page: 1,
      size: 999,
    })
      .then((res) => {
        let newActions = res.data.rows.map((item) => {
          let timeSpace = new Date().valueOf() - new Date(item.expirationDate);
          return {
            ...item,
            img: item.img,
            leftTime: moment(timeSpace).format('DD-hh:mm:ss'),
            selected: false,
          };
        });
        newActions = this.state.auctions.concat(newActions);

        this.setState({
          auctions: newActions,
        });
      })
      .catch((err) => {
        console.log('查询拍卖列表出错' + err);
      });
  };

  renderComponent = () => {
    let {auctions, querying} = this.state;

    return (
      <View style={{backgroundColor: '#160231', flex: 1, padding: 0}}>
        <NormalHeader
          navigation={this.props.navigation}
          text={I18n.t('home.create_room')}
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />

        <KeyboardAvoidingView
          behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
          style={{flex: 1}}>
          <ScrollView style={{padding: 20, flex: 1, paddingBottom: 0}}>
            <Text
              style={{
                color: 'white',
                margin: 8,
                fontWeight: 'bold',
                fontSize: 16,
              }}>
              Topic
            </Text>
            <TextInput
              style={{
                // padding: 22,
                backgroundColor: '#fff',
                // marginBottom: 20,
                borderRadius: 22,
                height: 40,
                paddingLeft: 22,
                paddingTop: 12,
              }}
              placeholder={I18n.t('create_room.add_topic')}
              placeholderTextColor="#a1a1a1"
              multiline
              onChangeText={(text) => {
                this.setState({
                  name: text,
                });
              }}></TextInput>
            <Text
              style={{
                color: 'white',
                margin: 8,
                fontWeight: 'bold',
                fontSize: 16,
              }}>
              Notice
            </Text>
            <TextInput
              style={{
                padding: 22,
                backgroundColor: '#fff',
                // marginBottom: 20,
                borderRadius: 22,
                height: 150,
                paddingTop: 22,
              }}
              placeholder={'Enter the notic of the chat room'}
              placeholderTextColor="#a1a1a1"
              multiline
              onChangeText={(text) => {
                this.setState({
                  notice: text,
                });
              }}></TextInput>
            <View
              style={{
                marginTop: 20,
                borderRadius: 22,
                marginBottom: 20,
              }}>
              <TouchableWithoutFeedback
                onPress={() => {
                  this.setState({
                    showPassword: !this.state.showPassword,
                  });
                }}>
                <View
                  style={{
                    flex: 1,
                    height: 40,
                    backgroundColor: '#571DAA',
                    borderRadius: 20,
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}>
                  <Text
                    style={{
                      flex: 1,
                      marginLeft: 20,
                      color: 'white',
                      fontWeight: 'bold',
                    }}>
                    Password
                  </Text>
                  <Image
                    style={{marginRight: 20}}
                    source={
                      this.state.showPassword
                        ? require('../../assets/room/up.png')
                        : require('../../assets/room/down.png')
                    }
                  />
                </View>
              </TouchableWithoutFeedback>
              {this.state.showPassword ? (
                <TextInput
                  style={{
                    // padding: 22,
                    backgroundColor: '#fff',
                    marginBottom: 20,
                    borderRadius: 22,
                    height: 40,
                    paddingLeft: 22,
                    paddingTop: 12,
                  }}
                  placeholder="password"
                  placeholderTextColor="#a1a1a1"
                  multiline
                  onChangeText={(text) => {
                    this.setState({
                      password: text,
                    });
                  }}></TextInput>
              ) : null}
            </View>
            <View
              style={{
                borderRadius: 22,
                marginBottom: 20,
              }}>
              <TouchableWithoutFeedback
                onPress={() => {
                  this.setState({
                    createPaidRoom: !this.state.createPaidRoom,
                  });
                }}>
                <View
                  style={{
                    flex: 1,
                    height: 40,
                    backgroundColor: '#571DAA',
                    borderRadius: 20,
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}>
                  <Text
                    style={{
                      flex: 1,
                      marginLeft: 20,
                      color: 'white',
                      fontWeight: 'bold',
                    }}>
                    Create Paid Room
                  </Text>
                  <Image
                    style={{marginRight: 20, width: 20, height: 20}}
                    source={
                      this.state.createPaidRoom
                        ? require('../../assets/common/checkbox.png')
                        : require('../../assets/common/checkbox-empty.png')
                    }
                  />
                </View>
              </TouchableWithoutFeedback>
            </View>
            {!this.props.userInfo.disableGift ? (
              <View
                style={{
                  borderRadius: 22,
                  marginBottom: 20,
                }}>
                <TouchableWithoutFeedback
                  onPress={() => {
                    this.setState({
                      showAuction: !this.state.showAuction,
                    });
                  }}>
                  <View
                    style={{
                      flex: 1,
                      height: 40,
                      backgroundColor: '#571DAA',
                      borderRadius: 20,
                      flexDirection: 'row',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}>
                    <Text
                      style={{
                        flex: 1,
                        marginLeft: 20,
                        color: 'white',
                        fontWeight: 'bold',
                      }}>
                      Auctions
                    </Text>
                    <Image
                      style={{marginRight: 20}}
                      source={
                        this.state.showAuction
                          ? require('../../assets/room/up.png')
                          : require('../../assets/room/down.png')
                      }
                    />
                  </View>
                </TouchableWithoutFeedback>
                {this.state.showAuction ? (
                  <View
                    style={{
                      width: '100%',
                      borderRadius: 20,
                      backgroundColor: 'white',
                      padding: 20,
                      flexDirection: 'row',
                      flexWrap: 'wrap',
                      marginBottom: 20,
                    }}>
                    {auctions.length == 0 ? (
                      <Text style={{width: '100%', textAlign: 'center'}}>
                        no valid auctions.
                      </Text>
                    ) : (
                      auctions.map((item) => {
                        return (
                          <TouchableOpacity
                            style={{
                              marginRight: 10,
                            }}
                            onPress={() => {
                              let newAuctions = auctions.map((cItem) => {
                                if (cItem.auctionId == item.auctionId) {
                                  cItem.selected = !cItem.selected;
                                }
                                return cItem;
                              });

                              console.log(newAuctions);

                              this.setState({
                                auctions: newAuctions,
                              });
                            }}
                            key={item.auctionId}>
                            <LinearGradient
                              style={{padding: 1, borderRadius: 10}}
                              start={{x: 0, y: 1}}
                              end={{x: 1, y: 1}}
                              colors={
                                !item.selected
                                  ? ['white', 'white']
                                  : ['#CE18EC', '#6601F5']
                              }>
                              <View
                                style={{
                                  backgroundColor: 'white',
                                  flex: 1,
                                  borderRadius: 10,
                                  justifyContent: 'center',
                                  alignItems: 'center',
                                }}>
                                <Image
                                  style={{
                                    width: 60,
                                    height: 60,
                                    margin: 10,
                                    borderRadius: 10,
                                  }}
                                  source={{uri: item.img}}></Image>
                                <Text style={{marginBottom: 5}}>
                                  {item.name}
                                </Text>
                              </View>
                            </LinearGradient>
                          </TouchableOpacity>
                        );
                      })
                    )}
                  </View>
                ) : null}
              </View>
            ) : null}
            {/* <View
              style={{
                backgroundColor: '#fff',
                borderRadius: 22,
                paddingLeft: 20,
                paddingRight: 20,
              }}>
              <TouchableOpacity
                style={{
                  height: 40,
                  flexDirection: 'row',
                  alignContent: 'center',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
                onPress={() => {
                  this.setState({
                    showAdvance: !this.state.showAdvance,
                  });
                }}>
                <Text style={{flex: 1, color: '#7104F4', fontWeight: 'bold'}}>
                  {I18n.t('create_room.advanced_info')}
                </Text>
                <Image
                  style={{width: 20, height: 20}}
                  source={require('../../assets/common/arrow_down.png')}
                />
              </TouchableOpacity>
              {this.state.showAdvance ? (
                <View>
                  <TouchableOpacity
                    style={{paddingTop: 20, paddingBottom: 20}}
                    onPress={() => {
                      ImagePicker.launchImageLibrary(
                        {
                          mediaType: 'photo',
                          includeBase64: false,
                          maxHeight: 600,
                          maxWidth: 600,
                        },
                        (res) => {
                          if (!res.errorCode && res.uri) {
                            this.setState({
                              topicImage: res.uri,
                            });
                          }
                        },
                      );
                    }}>
                    {this.state.topicImage ? (
                      <Image
                        style={{
                          width: '100%',
                          height: 200,
                          alignSelf: 'center',
                        }}
                        source={{uri: this.state.topicImage}}
                        resizeMode="cover"
                      />
                    ) : (
                      <Image
                        style={{
                          width: 60,
                          height: 60,
                          alignSelf: 'center',
                        }}
                        source={require('../../assets/room/add.png')}
                      />
                    )}
                  </TouchableOpacity>
                  <TextInput
                    style={{
                      backgroundColor: '#fff',
                      marginBottom: 20,
                      borderRadius: 22,
                      height: 150,
                      paddingTop: 10,
                    }}
                    placeholder={I18n.t('create_room.information')}
                    placeholderTextColor="#a1a1a1"
                    multiline
                    onChangeText={(text) => {
                      this.setState({
                        introduction: text,
                      });
                    }}></TextInput>
                </View>
              ) : null}
            </View>
             */}
            <LinearButton
              text={I18n.t('home.create')}
              onPress={this.createRoom}
              loading={querying}
              buttonStyle={{marginBottom: 50}}
            />
            <View style={{flex: 1}} />
          </ScrollView>
        </KeyboardAvoidingView>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
});

const mapDispatchToProps = (dispatch) => ({
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
  setCurrentRoom: (item) => dispatch(setCurrentRoom(item)),
  setRoomKey: (item) => dispatch(setRoomKey(item)),
});

export default connect(mapStateToProps, mapDispatchToProps)(CreateRoomScreen);
